---
title: Configuring Clients<br/>(i.e. System Under Test)
shortTitle: Configuring Clients
layout: page
pageOrder: 2
section: 'Proxy'
subsection: true
sitemap:
  priority: 0.7
  changefreq: 'monthly'
  lastmod: 2019-11-10T08:00:00+01:00
---

<p>MockServer provides the following types of proxy:</p>

<ul>
    <li><a href="#port_forwarding"><strong>Port Forwarding</strong></a>
        <ul>
            <li>all requests for a specific local port are forwarded to a different (local or remote) port and hostname for the system being proxied</li>
        </ul>
    </li>
    <li><a href="#web_secure_web_proxy"><strong>Web Proxy</strong></a> (i.e. HTTP proxy)
        <ul>
            <li>each request is forwarded dynamically using its Host header</li>
        </ul>
    </li>
    <li><a href="#web_secure_web_proxy"><strong>Secure Web Proxy</strong></a> (i.e. HTTPS tunneling proxying)
        <ul>
            <li>requests are forwarded using a CONNECT request that sets up an HTTP tunnel</li>
            <li>an SSL certificate is auto-generated allowing encrypted HTTPS traffic to be recorded transparently</li>
        </ul>
    </li>
    <li><a href="#socks_proxy"><strong>SOCKS Proxy</strong></a> (i.e. dynamic port forwarding)
        <ul>
            <li>requests are forwarded using a SOCK CONNECT CMD request that established a socket tunnel</li>
            <li>if the traffic is encrypted an SSL certificate is auto-generated allowing SSL traffic to be recorded transparently</li>
        </ul>
    </li>
</ul>

<p>The port forwarding and the SOCKS proxy are the most transparent and typically don't require any code changes.  However the Web Proxy and Secure Web Proxy ensure only configured clients are proxied and that multiple services can be simultaneously proxies.</p>

<a id="port_forwarding" class="anchor" href="#port_forwarding">&nbsp;</a>

<h3>Port Forwarding</h3>

<h4>Client</h4>

<p>Port forwarding is very simple as it does not require any code changes. The port forwarding proxy is configured to send all received requests to remote port and host.</p>

<p>Although the port forwarding proxy is the simplest proxy is can only proxy a single remote port and host. To forward multiple ports, multiple port forwarding proxies, should be run as separate processes.</p>

<p>There are two main approaches for routing requests via the port forwarding proxy.</p>

<ol>
	<li>Update the remote service host and port used by the client, typically this is either hard coded or in a configuration file. Change the remote service host and port to the host and port where the proxy is running.</li>
	<li>Add entry to the
		<strong>/etc/hosts</strong> file to map one or more remote domain names to the machine where the proxy is running. This approach will not require any configuration file changes as the operating system will resolve the remote domain name to matching where the proxy is running. However, this approach will only work if it is possible to start MockServer locally on the same port the client is connecting to on the remote machine.
	</li>
</ol>

<h4>Proxy</h4>

<p>To run the Port Forwarding Proxy the following values need to be provided to MockServer:</p>

<ul>
	<li><strong>serverPort</strong> - specifies the HTTP and HTTPS port for the MockServer.</li>
	<li><strong>proxyRemotePort</strong> - specifies the port to forward all proxy requests to.</li>
	<li><strong>proxyRemoteHost</strong> - specified the host to forward all proxy requests to as a domain name or ip address. If no value is provided when <strong>proxyRemotePort</strong> has been specified, the default <span class="string_literal">"localhost"</span> is used.</li>
</ul>

<p>For details of how to run MockServer with the above values configured see <a href="/mock_server/running_mock_server.html">Running MockServer</a></p>

<a id="web_secure_web_proxy" class="anchor" href="#web_secure_web_proxy">&nbsp;</a>

<h3>Web Proxy & Secure Web Proxy</h3>

<h4>Client</h4>

<p>To use the Web Proxy and Secure Web Proxy HTTP clients must be configured correctly.</p>

<p>Example code or screen-shots is shown below explaining how to configure the following clients:</p>

<ul>
	<li><a href="#java_jdk_http_url_connection">Java JDK HttpURLConnection</a></li>
	<li><a href="#apache_http_client">Apache HttpClient</a></li>
	<li><a href="#spring_rest_template">Spring RestTemplate</a></li>
	<li><a href="#spring_web_client">Spring WebClient</a></li>
	<li><a href="#google_http_client">Google HTTP Client</a></li>
	<li><a href="#jetty_http_client">Jetty HttpClient</a></li>
	<li><a href="#jersey_client">Jersey Client</a></li>
	<li><a href="#grizzly_async_http_client">Grizzly AsyncHttpClient</a></li>
	<li><a href="#apple_mac_http_https">Apple Mac HTTP & HTTPS (i.e. Chrome, Safari, Firefox, etc)</a></li>
</ul>

<h4>Proxy</h4>

<p>To run the Web Proxy or Secure Web Proxy the following values need to be provided to MockServer:</p>

<ul>
	<li><strong>serverPort</strong> - specifies the HTTP and HTTPS port for the MockServer.</li>
</ul>

<p>For details of how to run MockServer with the above values configured see <a href="/proxy/running_mock_server_proxy.html">Running MockServer</a></p>

<a id="java_jdk_http_url_connection" class="anchor" href="#java_jdk_http_url_connection">&nbsp;</a>

<h4>Java JDK HttpURLConnection (HTTP)</h4>

<p>Configure the Web or Secure Web Proxy with an <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html">HttpURLConnection</a> from the Java JDK, as follows:</p>

<pre><code class="code"><span class="keyword">private</span> HttpURLConnection sendRequestViaProxy(URL url) throws IOException {
    Proxy proxy = <span class="keyword">new</span> Proxy(Proxy.Type.<span class="constant">HTTP</span>, <span class="keyword">new</span> InetSocketAddress(System.getProperty(<span class="string_literal">"http.proxyHost"</span>), Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>))));
    <span class="keyword">return</span> (HttpURLConnection) url.openConnection(proxy);
}</code></pre>

<a id="apache_http_client" class="anchor" href="#apache_http_client">&nbsp;</a>

<h4>Apache HttpClient (HTTP)</h4>

<p>Configure the Web or Secure Web Proxy with an <a target="_blank" href="https://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>, as follows:</p>

<pre><code class="code">HttpHost httpHost = <span class="keyword">new</span> HttpHost(System.getProperty(<span class="string_literal">"http.proxyHost"</span>), Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>)));
DefaultProxyRoutePlanner defaultProxyRoutePlanner = <span class="keyword">new</span> DefaultProxyRoutePlanner(httpHost);
HttpClient httpClient = HttpClients.custom().setRoutePlanner(defaultProxyRoutePlanner).build();</code></pre>

<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/test/java/org/mockserver/examples/proxy/web/controller">mockserver-example</a> project contains an example of using the Web Proxy (i.e. HTTP Proxy) with a Apache HttpClient called
    <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/main/java/org/mockserver/examples/proxy/service/apacheclient/BookServiceApacheHttpClient.java">BookServiceApacheHttpClient</a> that demonstrates a fully working example.</p>

<a id="spring_rest_template" class="anchor" href="#spring_rest_template">&nbsp;</a>

<h4>Spring RestTemplate</h4>

<p>Configure the Web or Secure Web Proxy with a <a target="_blank" href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html">Spring RestTemplate</a>, as follows:</p>

<pre><code class="code">RestTemplate restTemplate = <span class="keyword">new</span> RestTemplate();
HttpHost httpHost = <span class="keyword">new</span> HttpHost(
        System.getProperty(<span class="string_literal">"http.proxyHost"</span>),
        Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>))
);
DefaultProxyRoutePlanner defaultProxyRoutePlanner = <span class="keyword">new</span> DefaultProxyRoutePlanner(httpHost);
HttpClient httpClient = HttpClients.custom().setRoutePlanner(defaultProxyRoutePlanner).build();
restTemplate.setRequestFactory(<span class="keyword">new</span> HttpComponentsClientHttpRequestFactory(httpClient));</code></pre>

<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/test/java/org/mockserver/examples/proxy/web/controller">mockserver-example</a> project contains an example of using the Web Proxy (i.e. HTTP Proxy) with a Spring RestTemplate called
    <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/main/java/org/mockserver/examples/proxy/service/springclient/BookServiceSpringRestTemplate.java">BookServiceSpringRestTemplate</a> that demonstrates a fully working example.</p>

<a id="spring_web_client" class="anchor" href="#spring_web_client">&nbsp;</a>

<h4>Spring WebClient</h4>

<p>Configure the Web or Secure Web Proxy with a <a target="_blank" href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-client">Spring RestTemplate</a>, as follows:</p>

<pre><code class="code">SslContext sslContext = <span class="keyword">new</span> NettySslContextFactory(<span class="keyword">new</span> MockServerLogger(getClass())).createClientSslContext(<span class="keyword">false</span>);
return WebClient.builder()
    .clientConnector(
        <span class="keyword">new</span> ReactorClientHttpConnector(
            HttpClient
                .create()
                .secure(SslProvider.builder().sslContext(sslContext).build())
                .proxy(proxy -> proxy
                    .type(ProxyProvider.Proxy.<span class="constant">HTTP</span>)
                    .host(System.getProperty(<span class="string_literal">"http.proxyHost"</span>))
                    .port(Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>)))
                )
        )
    )
    .baseUrl(baseUrl)
    .build();</code></pre>

<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/test/java/org/mockserver/examples/proxy/web/controller">mockserver-example</a> project contains an example of using the Web Proxy (i.e. HTTP Proxy) with a Spring WebClient called
    <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/main/java/org/mockserver/examples/proxy/service/springclient/BookServiceSpringWebClient.java">BookServiceSpringWebClient</a> that demonstrates a fully working example.</p>

<a id="google_http_client" class="anchor" href="#google_http_client">&nbsp;</a>

<h4>Google Client (HTTP)</h4>

<p>Configure the Web or Secure Web Proxy with a <a target="_blank"href="https://github.com/google/google-http-java-client">Google HTTP Client</a>, as follows:</p>

<pre><code class="code"><span class="keyword">private</span> HttpResponse sendRequestViaProxy(URL url, String method, <span class="annotation">@Nullable</span> HttpContent content) <span class="keyword">throws</span> IOException {
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    <span class="keyword">try</span> {
        ProxySelector.setDefault(new ProxySelector() {
            <span class="annotation">@Override</span>
            <span class="keyword">public</span> List&lt;Proxy&gt; select(URI uri) {
                <span class="keyword">return</span> Arrays.asList(new Proxy(Proxy.Type.<span class="constant">HTTP</span>, new InetSocketAddress(System.getProperty(<span class="string_literal">"http.proxyHost"</span>), Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>)))));
            }

            <span class="annotation">@Override</span>
            <span class="keyword">public void</span> connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                System.out.println(<span class="string_literal">"Connection could not be established to proxy at socket ["</span> + sa + <span class="string_literal">"]"</span>);
                ioe.printStackTrace();
            }
        });
        HttpRequestFactory requestFactory = <span class="keyword">new</span> NetHttpTransport().createRequestFactory();
        <span class="keyword">return</span> requestFactory.buildRequest(method, <span class="keyword">new</span> GenericUrl(url), content).execute();
    } <span class="keyword">finally</span> {
        ProxySelector.setDefault(defaultProxySelector);
    }
}</code></pre>

<a id="jetty_http_client" class="anchor" href="#jetty_http_client">&nbsp;</a>

<h4>Jetty HttpClient</h4>

<p>Configure the Web or Secure Web Proxy with a <a target="_blank" href="https://www.eclipse.org/jetty/documentation/current/http-client.html">Jetty HttpClient</a>, as follows:</p>

<p><strong>Jetty HttpClient 9.x</strong></p>

<pre><code class="code">HttpClient httpClient = <span class="keyword">new</span> HttpClient();
<span class="keyword">try</span> {
    httpClient.getProxyConfiguration().getProxies().add(<span class="keyword">new</span> HttpProxy(System.getProperty(<span class="string_literal">"http.proxyHost"</span>), Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>));
    httpClient.start();
} <span class="keyword">catch</span> (Exception e) {
    <span class="keyword">throw new</span> RuntimeException(<span class="string_literal">"Exception creating HttpClient"</span>, e);
}</code></pre>

<p><strong>Jetty HttpClient 8.x</strong></p>

<pre><code class="code">HttpClient httpClient = <span class="keyword">new</span> HttpClient();
<span class="keyword">try</span> {
    httpClient.setProxy(<span class="keyword">new</span> Address(System.getProperty(<span class="string_literal">"http.proxyHost"</span>), Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>));
    httpClient.start();
} <span class="keyword">catch</span> (Exception e) {
    <span class="keyword">throw new</span> RuntimeException(<span class="string_literal">"Exception creating HttpClient"</span>, e);
}</code></pre>

<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/test/java/org/mockserver/examples/proxy/web/controller">mockserver-example</a> project contains an example of using the Web Proxy (i.e. HTTP Proxy) with a Jetty HttpClient called
    <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/main/java/org/mockserver/examples/proxy/service/jettyclient/BookServiceJettyHttpClient.java">BookServiceJettyHttpClient</a> that demonstrates a fully working example.</p>

<a id="jersey_client" class="anchor" href="#jersey_client">&nbsp;</a>

<h4>Jersey Client</h4>

<p>Configure the Web or Secure Web Proxy with a <a target="_blank" href="https://jersey.java.net/documentation/latest/client.html">Jersey Client</a>, as follows:</p>

<pre><code class="code">ClientConfig clientConfig = <span class="keyword">new</span> ClientConfig().register(<span class="keyword">new</span> JacksonFeature())
                                              .connectorProvider(<span class="keyword">new</span> ApacheConnectorProvider());
clientConfig.property(ClientProperties.<span class="constant">PROXY_URI</span>, <span class="string_literal">"http://"</span> + System.getProperty(<span class="string_literal">"http.proxyHost"</span>) + <span class="string_literal">":"</span> + System.getProperty(<span class="string_literal">"http.proxyPort"</span>));
Client client = ClientBuilder.newClient(clientConfig);</code></pre>


<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/test/java/org/mockserver/examples/proxy/web/controller">mockserver-example</a> project contains an example of using the Web Proxy (i.e. HTTP Proxy) with a Jersey Client called
    <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/main/java/org/mockserver/examples/proxy/service/jerseyclient/BookServiceJerseyClient.java">BookServiceJerseyClient</a> that demonstrates a fully working example.</p>

<a id="grizzly_async_http_client" class="anchor" href="#grizzly_async_http_client">&nbsp;</a>

<h4>Grizzly AsyncHttpClient</h4>

<p>Configure the Web or Secure Web Proxy with a <a target="_blank"href="https://github.com/AsyncHttpClient/async-http-client">Grizzly AsyncHttpClient</a>, as follows:</p>

<pre><code class="code">AsyncHttpClientConfig.Builder clientConfigBuilder = <span class="keyword">new</span> AsyncHttpClientConfig.Builder();
clientConfigBuilder.setProxyServerSelector(ProxyUtils.createProxyServerSelector(HttpProxy.proxySelector()));
AsyncHttpClient asyncHttpClient = <span class="keyword">new</span> AsyncHttpClient(clientConfigBuilder.build());</code></pre>


<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/ec6e389cde20150429e22b8e9f8a60f57c8a24c3/mockserver-examples">mockserver-example</a> project contains an example of using the Web Proxy (i.e. HTTP Proxy) with a Grizzly AsyncHttpClient called
	<a target="_blank"href="https://github.com/mock-server/mockserver/blob/ec6e389cde20150429e22b8e9f8a60f57c8a24c3/mockserver-examples/src/main/java/org/mockserver/service/grizzlyclient/BookServiceGrizzlyHttpClient.java">BookServiceGrizzlyHttpClient</a> that demonstrates a fully working example.</p>

<a id="apple_mac_http_https" class="anchor" href="#apple_mac_http_https">&nbsp;</a>

<h4>Apple Mac HTTP & HTTPS (i.e. Chrome, Safari, Firefox, etc)</h4>

<p>The Apple Mac can be configure to send all HTTP or HTTPS request via a proxy. This is done in the proxy settings in System Preferences > Network > Advanced > Proxies, as follows:</p>

<p><strong>1. System Preferences</strong></p>

<p><img src="/images/mac_proxy_configuration/system_preferences.png" alt="Apple Mac System Preferences" style="max-width:80%;"></p>

<p><strong>2. Network Preferences</strong></p>

<p><img src="/images/mac_proxy_configuration/system_preferences_network.png" alt="Apple Mac Network Preferences" style="max-width:80%;"></p>

<p><strong>3. Web Proxy Settings (HTTP requests)</strong></p>

<p><img src="/images/mac_proxy_configuration/network_web_proxy.png" alt="Web Proxy Configuration" style="max-width:80%;"></p>

<p><strong>4. Secure Web Proxy Settings (HTTPS requests)</strong></p>

<p><img src="/images/mac_proxy_configuration/network_secure_web_proxy.png" alt="Secure Web Proxy Configuration" style="max-width:80%;"></p>

<a id="socks_proxy" class="anchor" href="#socks_proxy">&nbsp;</a>

<h3>SOCKS Proxy</h3>

<h4>Client</h4>

<p>The SOCKS Proxy operates at the socket level, therefore, it is possible to configure a single client, an entire JVM or an entire operating system to send all network requests via the SOCKS Proxy.</p>

<p>Example code or screen-shots is shown below explaining how to configure the following clients:</p>

<ul>
	<li><a href="#socks_apache_http_client">Apache HttpClient</a></li>
	<li><a href="#socks_java_jdk_http_url_connection">Java JDK HttpURLConnection</a></li>
	<li><a href="#socks_google_http_client">Google HTTP Client</a></li>
	<li><a href="#socks_jvm_configuration">Java Virtual Machine Network Stack</a></li>
	<li><a href="#socks_mac_os">Apple Mac Network Stack (i.e. SOCKS)</a></li>
</ul>

<h4>Proxy</h4>

<p>To run the SOCKS Proxy the following values need to be provided to MockServer:</p>

<ul>
	<li><strong>serverPort</strong> - specifies the SOCKS port for the MockServer.</li>
</ul>

<p>For details of how to run MockServer with the above values configured see <a href="/proxy/running_mock_server_proxy.html">Running MockServer</a></p>

<a id="socks_apache_http_client" class="anchor" href="#socks_apache_http_client">&nbsp;</a>

<h4>Apache HttpClient (SOCKS)</h4>

<p>Configure the SOCKS Proxy with an <a target="_blank" href="https://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>, as follows:</p>

<pre><code class="code">Registry&lt;ConnectionSocketFactory&gt; socketFactoryRegistry = RegistryBuilder.&lt;ConnectionSocketFactory&gt;create()
        .register(<span class="string_literal">"http"</span>, <span class="keyword">new</span> ConnectionSocketFactory() {

            <span class="keyword">public</span> Socket createSocket(<span class="keyword">final</span> HttpContext context) <span class="keyword">throws</span> IOException {
                <span class="keyword">return new</span> Socket(
                        java.net.Proxy.Type.<span class="constant">SOCKS</span>,
                        <span class="keyword">new</span> InetSocketAddress(
                                System.getProperty(<span class="string_literal">"http.proxyHost"</span>),
                                Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>))
                        )));
            }

            <span class="keyword">public</span> Socket connectSocket(
                    <span class="keyword">final int</span> connectTimeout,
                    <span class="keyword">final</span> Socket socket,
                    <span class="keyword">final</span> HttpHost host,
                    <span class="keyword">final</span> InetSocketAddress remoteAddress,
                    <span class="keyword">final</span> InetSocketAddress localAddress,
                    <span class="keyword">final</span> HttpContext context) <span class="keyword">throws</span> IOException {
                Socket sock;
                <span class="keyword">if</span> (socket != <span class="keyword">null</span>) {
                    sock = socket;
                } <span class="keyword">else</span> {
                    sock = createSocket(context);
                }
                <span class="keyword">if</span> (localAddress != <span class="keyword">null</span>) {
                    sock.bind(localAddress);
                }
                <span class="keyword">try</span> {
                    sock.connect(remoteAddress, connectTimeout);
                } <span class="keyword">catch</span> (SocketTimeoutException ex) {
                    throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress());
                }
                <span class="keyword">return</span> sock;
            }

        })
        .build();

PoolingHttpClientConnectionManager clientConnectionManager = <span class="keyword">new</span> PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClient httpClient = HttpClients.custom()
        .setConnectionManager(clientConnectionManager)
        .build();</code></pre>

<a id="socks_java_jdk_http_url_connection" class="anchor" href="#socks_java_jdk_http_url_connection">&nbsp;</a>

<h4>Java JDK HttpURLConnection (SOCKS)</h4>

<p>Configure the SOCKS Proxy with an <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html">HttpURLConnection</a> from the Java JDK, as follows:</p>

<pre><code class="code"><span class="keyword">private</span> HttpURLConnection sendRequestViaProxy(URL url) throws IOException {
    Proxy proxy = <span class="keyword">new</span> Proxy(Proxy.Type.<span class="constant">SOCKS</span>, <span class="keyword">new</span> InetSocketAddress(System.getProperty(<span class="string_literal">"http.proxyHost"</span>), Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>))));
    <span class="keyword">return</span> (HttpURLConnection) url.openConnection(proxy);
}</code></pre>

<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/test/java/org/mockserver/examples/proxy/web/controller">mockserver-example</a> project contains an example of using the SOCKS Proxy with a HttpURLConnection called
    <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/main/java/org/mockserver/examples/proxy/service/javaclient">BookServiceJavaHttpClient</a> that demonstrates a fully working example.</p>

<a id="socks_google_http_client" class="anchor" href="#socks_google_http_client">&nbsp;</a>

<h4>Google HTTP Client (SOCKS)</h4>

<p>Configure the SOCKS Proxy with a <a target="_blank"href="https://github.com/google/google-http-java-client">Google HTTP Client</a>, as follows:</p>

<pre><code class="code"><span class="keyword">private</span> HttpResponse sendRequestViaProxy(URL url, String method, <span class="annotation">@Nullable</span> HttpContent content) <span class="keyword">throws</span> IOException {
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    <span class="keyword">try</span> {
        ProxySelector.setDefault(new ProxySelector() {
            <span class="annotation">@Override</span>
            <span class="keyword">public</span> List&lt;Proxy&gt; select(URI uri) {
                <span class="keyword">return</span> Arrays.asList(new Proxy(Proxy.Type.<span class="constant">SOCKS</span>, new InetSocketAddress(System.getProperty(<span class="string_literal">"http.proxyHost"</span>), Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>)))));
            }

            <span class="annotation">@Override</span>
            <span class="keyword">public void</span> connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                System.out.println(<span class="string_literal">"Connection could not be established to proxy at socket ["</span> + sa + <span class="string_literal">"]"</span>);
                ioe.printStackTrace();
            }
        });
        HttpRequestFactory requestFactory = <span class="keyword">new</span> NetHttpTransport().createRequestFactory();
        <span class="keyword">return</span> requestFactory.buildRequest(method, <span class="keyword">new</span> GenericUrl(url), content).execute();
    } <span class="keyword">finally</span> {
        ProxySelector.setDefault(defaultProxySelector);
    }
}</code></pre>

<p>The <a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/test/java/org/mockserver/examples/proxy/web/controller">mockserver-example</a> project contains an example of using the SOCKS Proxy with a Google HTTP Client called
	<a target="_blank"href="https://github.com/mock-server/mockserver/tree/master/mockserver-examples/src/main/java/org/mockserver/examples/proxy/service/googleclient/BookServiceGoogleHttpClient.java">BookServiceGoogleHttpClient</a> that demonstrates a fully working example.</p>

<a id="socks_jvm_configuration" class="anchor" href="#socks_jvm_configuration">&nbsp;</a>

<h4>JVM Configuration</h4>

<p>It is possible to enable the SOCK proxy for the entire JVM, as follows:</p>

<pre><code class="code">ProxySelector.setDefault(<span class="keyword">new</span> ProxySelector() {
    <span class="annotation">@Override</span>
    <span class="keyword">public</span> List&lt;java.net.Proxy&gt; select(URI uri) {
        <span class="keyword">return</span> Arrays.asList(
                new java.net.Proxy(
                            java.net.Proxy.Type.<span class="constant">SOCKS</span>,
                        <span class="keyword">new</span> InetSocketAddress(
                                System.getProperty(<span class="string_literal">"http.proxyHost"</span>),
                                Integer.parseInt(System.getProperty(<span class="string_literal">"http.proxyPort"</span>))
                        )
                )
        );
    }

    <span class="attribute_name">@Override</span>
    <span class="keyword">public void</span> connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        logger.error(<span class="string_literal">"Connection could not be established to proxy at socket ["</span> + sa + <span class="string_literal">"]"</span>, ioe);
    }
});</code></pre>

<a id="socks_mac_os" class="anchor" href="#socks_mac_os">&nbsp;</a>

<h4>Apple Mac Network Stack (SOCKS)</h4>

<p>The Apple Mac can be configure to send all network requests via a SOCKS proxy. This is done in the proxy settings in System Preferences > Network > Advanced > Proxies, as follows:</p>

<p><strong>1. System Preferences</strong></p>

<p><img src="/images/mac_proxy_configuration/system_preferences.png" alt="Apple Mac System Preferences" style="max-width:80%;"></p>

<p><strong>2. Network Preferences</strong></p>

<p><img src="/images/mac_proxy_configuration/system_preferences_network.png" alt="Apple Mac Network Preferences" style="max-width:80%;"></p>

<p><strong>3. SOCKS Proxy Settings</strong></p>

<p><img src="/images/mac_proxy_configuration/network_socks_proxy.png" alt="SOCKS Proxy Configuration" style="max-width:80%;"></p>
